package com.topisv.tms.web.stock.preinstorage;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.stock.instorage.InstorageBill;
import com.topisv.tms.entity.stock.instorage.InstorageCountItem;
import com.topisv.tms.entity.stock.instorage.pre.InstorageBillItemPre;
import com.topisv.tms.entity.stock.instorage.pre.InstorageBillPre;
import com.topisv.tms.service.EdiGoodsSkuService;
import com.topisv.tms.service.stock.instorage.InstorageBillService;
import com.topisv.tms.service.stock.preinstorage.PreInstorageService;
import com.topisv.tms.utils.vo.PreInstorageVo;
import com.topisv.tms.web.base.BaseDataTableController;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import net.sf.json.JSONObject;

/**
 * 预约入库Control
 *  Date          Author       Version       Description
 * ----------------------------------------------------------
 *  2014-7-3      CC            1.0           Create
 */
@Controller
@RequestMapping(value = "/v2/preInstorageBill")
public class PreInstorageBillController extends BaseDataTableController{
	private Logger log = LoggerFactory.getLogger(getClass());
	@Autowired
	private PreInstorageService preInstorageService;
	@Autowired
	private EdiGoodsSkuService ediGoodsSkuService;
	@Autowired
	private InstorageBillService instorageBillService;

	@RequestMapping("queryPreInstorage")
	public String queryPreInstorage(HttpServletRequest request,Model model
			,@RequestParam(value = "page", defaultValue = "1") int pageNumber
			,@RequestParam(value = "pageSize", defaultValue = "20") int pageSize
			,@DateTimeFormat(pattern="yyyy-MM-dd")@RequestParam(value = "_fromDate", required=false) Date fromDate
			,@DateTimeFormat(pattern="yyyy-MM-dd")@RequestParam(value = "_toDate", required=false) Date toDate
			) {
		try {
			fillSelectValue(model, null);
		} catch (Exception e) {
			log.info("queryPreInstorage case error", e);
			
		}
		return "preinstorage/preInstorage";
	}
	
	@RequestMapping(value = "page",method = RequestMethod.POST)
	public void page(@RequestBody JSONParam[] paramJson, HttpServletRequest request,HttpServletResponse response){
		try {
			// 客户端参数
			QueryParamHolder paramHolder = collectParam(paramJson,"_");
			Map<String, Object> searchParams = paramHolder.getSearchParams();
			String fromTm = (String)searchParams.get("GTE_createTm");
			String toTm = (String)searchParams.get("LT_createTm");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			if(!StringUtils.isBlank(fromTm)){
				searchParams.put("GTE_createTm",sdf.parse(fromTm));
			}
			if(!StringUtils.isBlank(toTm)){
				searchParams.put("LT_createTm",sdf.parse(toTm));
			}
			Page<InstorageBillPre> page = preInstorageService.queryInstorageBillPre(paramHolder);
			// 封装查询结果
			response.getWriter().print(bulidJSON(page));
		} catch (Exception e) {
			e.printStackTrace();
			this.log.info(e.getMessage());
		}
	}
	
	/**
	 * 创建预约任务
	 * @param request
	 * @param preInstorageVo
	 * @return
	 */
	@RequestMapping("createPreInstorage")
	public String createPreInstorage(@ModelAttribute("vo")PreInstorageVo preInstorageVo) {
		try {
		    // 标记订单是否手动创建 419 yuangsheng
		    preInstorageVo.setManuelFlag(1);
		    // 标记订单是否手动创建 419 yuangsheng
			preInstorageService.saveInstorageBillPre(preInstorageVo);
		} catch (Exception e) {
			log.error("createPreInstorage case some error.",e);
		}
		return "redirect:/v2/preInstorageBill/queryPreInstorage";
	}
	/**
	 * 删除预约任务
	 * @param id
	 */
	@RequestMapping("deletePreInstorgaeInfo")
	@ResponseBody
	public String deletePreInstorgaeInfo(@RequestParam("id") String id){
		preInstorageService.deletePreInstorageInfo(Long.valueOf(id));
		return "true";
	}
	/**
	 * 查询预约任务
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("queryPreInstorageInfo/{id}")
	public String queryPreInstorageInfo(@PathVariable("id") String id,Model model){
		fillSelectValue(model, null);
		if (!"-1".equals(id)) {
			model.addAttribute("vo", preInstorageService.queryPreInstorageVo(id));
		}
		return "preinstorage/addpreinstorage";
	}
	@RequestMapping("queryInstorageCountItem")
	@ResponseBody
	public List<InstorageCountItem> queryInstorageCountItem(@RequestParam("billCode") String billCode){
		return preInstorageService.queryInstorageCountItem(billCode);
	}
	
	/**
	 * 导出预约清单
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "outexportExcel")
	public void outexportExcel(ServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "_");
		String fromTm = (String)searchParams.get("GTE_createTm");
		String toTm = (String)searchParams.get("LT_createTm");
		Date fromDate=null;
		Date toDate=null;
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(StringUtils.isNotEmpty(fromTm)){
			fromDate=sdf.parse(fromTm+" 00:00:00");
		}
		if(StringUtils.isNotEmpty(toTm)){
			toDate=sdf.parse(toTm+" 23:59:59");
		}
		String warehouseCode=(String)searchParams.get("EQ_inwarehouseCode");
		String customerCode=(String)searchParams.get("EQ_customerCode");
		String orderStatus=(String)searchParams.get("EQ_orderStatus");
		
		
		Map<String, Object> param = new HashMap<String, Object>();
		
		param.put("customerCode", customerCode);
		param.put("warehouseCode", warehouseCode);
		param.put("orderStatus", orderStatus);
		param.put("fromDate", fromDate);
		param.put("toDate", toDate);
		List<InstorageBillPre> billPre = preInstorageService.findByWhere(param);
		log.info("=======开始导出预约单=======");
		
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-disposition","attachment; filename=" + customerCode +fromTm + toTm+ ".xls");
		
		WritableWorkbook book  =  Workbook.createWorkbook(response.getOutputStream());
		WritableSheet sheet  =  book.createSheet( "Sheet1 ",0);
		//商家,仓库，商品名 ，货号，条码，数量
		sheet.setColumnView(0, 20);
		sheet.setColumnView(1, 20);
		sheet.setColumnView(2, 20);
		sheet.setColumnView(3, 20);
		sheet.setColumnView(4, 20);
		sheet.setColumnView(6, 20);
		
		Label label1 = new  Label(0,0 ,"商家名称");
		sheet.addCell(label1);
		Label label2 = new  Label(1,0 ,"仓库");
		sheet.addCell(label2);
		Label label3 = new  Label(2,0 ,"商品名");
		sheet.addCell(label3);
		Label label4 = new  Label(3,0 ,"货号");
		sheet.addCell(label4);
		Label label5 = new  Label(4,0 ,"条码");
		sheet.addCell(label5);
		Label label6 = new  Label(5,0 ,"数量");
		sheet.addCell(label6);
		int index_1 = 1;
		for(InstorageBillPre pre:billPre){
			List<InstorageBillItemPre> billItemPre = preInstorageService.findBillItemPreById(pre.getId());
			for(InstorageBillItemPre item : billItemPre){
				Label label01 = new  Label(0,index_1,pre.getCustomerCode());
				sheet.addCell(label01);
				Label label02 = new  Label(1,index_1,pre.getInwarehouseCode());
				sheet.addCell(label02);
				EdiGoodsSku goodSku = ediGoodsSkuService.findByCustomerCodeAndSku(pre.getCustomerCode(), item.getSkuCode());
				String skuName = "";
				if(goodSku != null){
					skuName=goodSku.getSkuName();
				}
				Label label03 = new  Label(2,index_1,skuName);
				sheet.addCell(label03);
				Label label04 = new  Label(3,index_1,item.getSkuBar());
				sheet.addCell(label04);
				Label label05 = new  Label(4,index_1,item.getSkuCode());
				sheet.addCell(label05);
				Label label06 = new  Label(5,index_1,item.getGoodsNum().toString());
				sheet.addCell(label06);
				index_1++;
			}
		}
		book.write();
        book.close();
        
        log.info("=======导出结束=======");
	}
	@RequestMapping(value = "printPreInstorage",method=RequestMethod.POST)
	public void printPreInstorage(ServletRequest request,HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			String billCode=request.getParameter("billCode");
			preInstorageService.updateInstorageBillPrintNum(billCode);
			json.put("status", "success");
			json.put("instorageBill", instorageBillService.findInstorageBillByAboutCode(billCode));
			json.put("instorageBillItemPreList",preInstorageService.getInstorageBillItemPreList(preInstorageService.findByBillCode(billCode).getId()));
		} catch (Exception e) {
			log.error("error",e);
			json.put("status","error");
			json.put("content",e.getMessage());
		}
		out.print(json.toString());
	}
	
	/**
	 * 验证sku在当前商家是否存在
	 * 
	 * @param 
	 * @return 
	 * @throws 
	 * @author Songlinhai
	 * @version 1.0.0
	 */
	@RequestMapping(value = "checkSku",method=RequestMethod.POST)
    public void checkSku(ServletRequest request,HttpServletResponse response) {
        JSONObject json = null;
        PrintWriter out = null;
        try {

            json = new JSONObject();
            out = response.getWriter();
            
            String status = "error";
            String content = null;
            String isBatchMgmt = null;
            String isShelfLifeMgmt = null;
            
            String customerCode=request.getParameter("customerCode");
            String sku = request.getParameter("sku");
            
            EdiGoodsSku ediGoodsSku = this.ediGoodsSkuService.findByCustomerCodeAndSku(customerCode, sku);
            
            if(ediGoodsSku != null){
                isBatchMgmt = ediGoodsSku.getIsBatchMgmt() == null ? "0" : ediGoodsSku.getIsBatchMgmt();
                isShelfLifeMgmt = ediGoodsSku.getIsShelfLifeMgmt() == null ? "0" : ediGoodsSku.getIsShelfLifeMgmt();
                status = "success";
            }else{
                content = "sku" + sku + "在商家" + customerCode + "下不存在";
            }
            
            json.put("status", status);
            json.put("content", content);
            json.put("isBatchMgmt", isBatchMgmt);
            json.put("isShelfLifeMgmt", isShelfLifeMgmt);
            
         } catch (Exception e) {
            log.error("error",e);
            json.put("status","error");
            json.put("content",e.getMessage());
        }
        out.print(json.toString());
    }
//	/**
//	 *设置商品名称以及规格
//	 * @param itemPreList
//	 */
//	 private List<InstorageBillItemPre> setGoodSkuDetail(InstorageBill bill,List<InstorageBillItemPre> itemPreList){
//		 for(InstorageBillItemPre itemPre:itemPreList){
//			 itemPre.setSkuName(ediGoodsSkuService.findBySkuAndCustomerCode(itemPre.getSkuCode(), bill.getCustomerCode()).getSkuName());
//			 itemPre.setSpec(ediGoodsSkuService.findBySkuAndCustomerCode(itemPre.getSkuCode(), bill.getCustomerCode()).getSpec());
//		 }
//		 return itemPreList;
//	 }
	
}
